from rest_framework import serializers
from scan.models import Machine, Account
from rest_framework.response import Response

class MachineSerializer(serializers.ModelSerializer):
    full_OSType = serializers.ReadOnlyField(source='get_OSType_display')
    full_Status = serializers.ReadOnlyField(source='get_Status_display')
    full_MachineType = serializers.ReadOnlyField(source='get_MachineType_display')
    full_CreateMethod = serializers.ReadOnlyField(source='get_CreateMethod_display')
    platfrom_source = serializers.SerializerMethodField()
    accounts_detail = serializers.SerializerMethodField()

    def get_platfrom_source(self, obj):
        return 'CMDB平台'

    def get_accounts_detail(self, obj):
        return AccountSerializer(obj.accounts.all(), many=True).data

    class Meta:
        model = Machine  # 序列化的数据库模型是什么？
        # 序列化返回的列信息有哪些
        #       fields =  __all__代表所有, fields = ['id', 'InstanceId']代表只显示这两列
        #       exclude = ['id']  # 除了id之外其他都展示
        fields = '__all__'
        read_only_fields = ('id', 'PublicIpAddresses')


class AccountSerializer(serializers.ModelSerializer):
    # Machine = MachineSerializer()  # 嵌套序列化器, 外键关联的字段名 = 类序列化名()
    def create(self, validated_data):
        """创建时需要加密"""
        validated_data['Password'] = validated_data['Password'] + '---'
        account = Account.objects.create(**validated_data)
        return account

    def update(self, instance, validated_data):
        """更新时需要加密"""
        validated_data['Password'] = validated_data['Password'] + '---'
        account = Account.objects.create(**validated_data)
        return account

    class Meta:
        model = Account
        fields = '__all__'
